package com.secneo.appshare.api;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import weibo4android.Status;
import weibo4android.User;
import weibo4android.Weibo;
import weibo4android.WeiboException;
import weibo4android.http.ImageItem;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Message;
import android.text.format.Time;
import android.util.Log;

import com.kaixin.connect.Kaixin;
import com.kaixin.connect.KaixinError;
import com.kaixin.connect.Util;
import com.mime.qweibo.OauthKey;
import com.mime.qweibo.QParameter;
import com.mime.qweibo.QWeiboRequest;
import com.renren.api.connect.android.AsyncRenren;
import com.renren.api.connect.android.Renren;
import com.secneo.appshare.R;
import com.secneo.appshare.common.Constants;

public class LocalStore {

    public static final String USER_SIMPLE_FIELDS = "name,tinyurl";
	
	private static LocalStore store;
	private Context ctx;
	private Activity storedActivity=null;


	private boolean[] accountLogin = {
			false,
			false,
			false,
			false,
			false,
	};
	//0:bangbang; 1:sina; 2:tencent; 3:renren: 4:kaixin
	
	//Sina related:
	private String token;
	private String tokenSecret;
	private Weibo sinaWeibo;
	private User sinaUser;
	
	//Renren related
	private Renren renrenStore;
	private AsyncRenren asyncRenren;
	private String userId;
	private String userName;
	private String picUrl;

	//tencent related
	private String tencentUserId;
	private String tencentUserName;
	private String tencentPicUrl;

	//kaixin related
	private String kaixinUserId;
	private String kaixinUserName;
	private String kaixinPicUrl;

	private String sinaLoginTime;
	private String renrenLoginTime;
	private String tencentLoginTime;
	private String kaixinLoginTime;
	
	

    public String getRenrenSessionKey() {
        return renrenStore.getSessionKey();
    }

    public String getRenrenSessionSecret() {
    	return renrenStore.getSessionSecret();
    }


    public String getKaixinAccessToken() {
    	Kaixin kaixin = Kaixin.getInstance();
        return kaixin.getAccessToken();
    }

    public String getKaixinAccessTokenSecret() {
    	Kaixin kaixin = Kaixin.getInstance();
        return kaixin.getAccessTokenSecret();
    }

	

	
	public void logoutSinaAccount() {
		token = "";
		tokenSecret = "";
		accountLogin[1] = false;

		SharedPreferences sp = ctx.getSharedPreferences(Constants.PRE_USER_INFO, Context.MODE_PRIVATE);
		Editor spEditor = sp.edit();
		spEditor.putString(Constants.ACCESS_TOKEN, token);
		spEditor.commit();
		spEditor.putString(Constants.ACCESS_TOKEN_SECRET, tokenSecret);
		spEditor.commit();		
	}
	public void logoutRenrenAccount() {
		renrenStore.logout(ctx);
		accountLogin[3] = false;
	}

	
	public void logoutTencentAccount() {
		Log.d("qq" , "logoutTencentAccount") ;
		setQWeiboAccessToken("") ;
		setQWeiboAccessTokenSecret("") ;
		accountLogin[2] = false;
	}

	public void logoutKaixinAccount() {
		Log.d("kaixin" , "logoutKaixinAccount") ;
		Kaixin kaixin = Kaixin.getInstance();
		kaixin.clearStorage(ctx);
		accountLogin[4] = false;
	}
	

	public boolean thereIsAccountLogin() {
		if(Constants.SWITCH_SINA_CUSTOM){
			return accountLogin[0] || accountLogin[1];
		}
		
		return accountLogin[0] || accountLogin[1] || accountLogin[2] || accountLogin[3] || accountLogin[4]; 
	}
	public boolean thereIsSnsAccountLogin() {
		if(Constants.SWITCH_SINA_CUSTOM){
			return accountLogin[1];
		}
		return accountLogin[1] || accountLogin[2] || accountLogin[3] || accountLogin[4]; 
	}
	
	
	private LocalStore(Context ctx) {
		store = null;
		this.ctx = ctx;
		token = "";
		tokenSecret = "";
		userName = "";
		userId = "";
		picUrl = "";
		
		initAllAccount();
	}
	
	public synchronized static LocalStore getLocaleStoreInstance(Context ctx)
	{
		if (store == null)
		{
			store = new LocalStore(ctx);
		}
		return store;
	}
	
	public synchronized static LocalStore getLocaleStoreInstance()
	{
		assert(store!=null);
		return store;
	}


	public boolean accountIsActive(int accountIndex){
		//0:bangbang; 1:sina; 2:tencent; 3:renren: 4:kaixin

		if(Constants.SWITCH_SINA_CUSTOM){
			if(accountIndex>1){
				return false;
			}
		}
		else{
			if(accountIndex>4){
				return false;
			}
		}
		return accountLogin[accountIndex];
	}


	public int getLocalSnsIconResource(){

		if(accountLogin[1]){
			return R.drawable.xinlang_icon;
		}
		else if(accountLogin[2]){
			return R.drawable.qq_small_icon;
		}
		else if(accountLogin[3]){
			return R.drawable.renren_small_icon;
		}
		else if(accountLogin[4]){
			return R.drawable.kaixin_small_icon;
		}
		else{
			return 0;
		}
	}

	
	public void setRenrenAccountActive() {
		if(!Constants.SWITCH_SINA_CUSTOM){
			accountLogin[3] = true;
			SaveCurrentTime("renren_login_time");
		}
	}
	public void setSinaAccountActive() {
		accountLogin[1] = true;
		SaveCurrentTime("sina_login_time");
	}
	public void setBangAccountActive() {
		accountLogin[0] = true;
	}
	public void setTencentAccountActive() {
		if(!Constants.SWITCH_SINA_CUSTOM){
			accountLogin[2] = true;
			SaveCurrentTime("tencent_login_time");
		}
	}
	public void setKaixinAccountActive() {
		if(!Constants.SWITCH_SINA_CUSTOM){
			accountLogin[4] = true;
			SaveCurrentTime("kaixin_login_time");
		}
	}
	
	public void logoutBangAccount() {
		
		if(accountLogin[1]){
			logoutSinaAccount();
		}
		if(!Constants.SWITCH_SINA_CUSTOM){
			if(accountLogin[2]){
				logoutTencentAccount();
			}
			if(accountLogin[3]){
				logoutRenrenAccount();
			}
			if(accountLogin[4]){
				logoutKaixinAccount();
			}
		}

		accountLogin[0] = false;
		accountLogin[1] = false;
		accountLogin[2] = false;
		accountLogin[3] = false;
		accountLogin[4] = false;
		
		SharedPreferences sp = ctx.getSharedPreferences(USER_DATA_PREF, ctx.MODE_PRIVATE);
		sp.edit().putString(UID_KEY, "").commit();
		sp.edit().putString(ANDROID_ID_KEY, "").commit();
		sp.edit().putString(NICKNAME_KEY, "").commit();
		sp.edit().putString(USER_AVATAR_KEY, "").commit();
	}
	

	public int getSmallIconResource(int snsType){

		switch(snsType){
			case Constants.SNS_INDEX_SINA://sina
				return R.drawable.xinlang_icon;
			case Constants.SNS_INDEX_TENCENT://tencent
				return R.drawable.qq_small_icon;
			case Constants.SNS_INDEX_RENREN://renren
				return R.drawable.renren_small_icon;
			case Constants.SNS_INDEX_KAIXIN://kaixin
				return R.drawable.kaixin_small_icon;
			default:
				return 0;
		}
	}
	
	

	private void getSinaWeibo(){
		if(sinaWeibo==null){
			sinaWeibo= new Weibo();
		}
	}
	

	public void initAllAccount(){

		initBangAccount();
		initSinaAccount();

		if(!Constants.SWITCH_SINA_CUSTOM){
			initRenrenAccount();
			initTencentAccount();
			initKaixinAccount();
		}
	}
	

	
	public boolean initBangAccount(){

		String uid = getUid();
		if(uid == null || uid.equals("")){
			accountLogin[0] = false;
		}
		else{
			accountLogin[0] = true;
		}

		return accountLogin[0];
	}
	
	
	public boolean initSinaAccount(){

		System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
		System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
		
//		boolean weiboLogin = getIntent().getBooleanExtra("weiboLogin", true);
		SharedPreferences sp = ctx.getSharedPreferences(Constants.PRE_USER_INFO, Context.MODE_WORLD_READABLE);

		token = sp.getString(Constants.ACCESS_TOKEN, "");
		tokenSecret = sp.getString(Constants.ACCESS_TOKEN_SECRET, "");
		
		if (tokenSecret.equals("")){
			accountLogin[1] = false;
		}
		else{
			accountLogin[1] = true;
		}

		getSinaWeibo();
		sinaWeibo.setToken(token, tokenSecret);

		return accountLogin[1];
	}
	
	
	public boolean initTencentAccount(){
		String tokenSecret = qWeiboAccessTokenSecret() ;
		if (tokenSecret.equals("")){
			accountLogin[2] = false;
		}
		else{
			accountLogin[2] = true;
		}
				
		return accountLogin[2];
	}
	
	public boolean initRenrenAccount(){
		if(renrenStore==null){
			renrenStore = new Renren(Constants.RENREN_API_KEY);
		}
		
        accountLogin[3] = this.renrenStore.restoreSessionKey(ctx);
        
		if(asyncRenren==null){
	        asyncRenren = new AsyncRenren(renrenStore);
		}

		return accountLogin[3];
	}
	
	public boolean initKaixinAccount(){
		Kaixin kaixin = Kaixin.getInstance();
		accountLogin[4] = kaixin.loadStorage(ctx);
		return accountLogin[4];
	}

	
	
	
	public void getRenrenUserInfo() {

        Bundle params = new Bundle();
        params.putString("method", "users.getLoggedInUser");
        
        String response = renrenStore.requestJSON(params);
		if(response.length()==0){
			return;
		}
		String uidStr = this.parseUserIdJson(response);
        if(uidStr.length()==0){
        	return;
        }

    	Log.e(uidStr, uidStr);
    	params.clear();
        params.putString("method", "users.getInfo");
        params.putString("uids", uidStr);
        params.putString("fields", USER_SIMPLE_FIELDS);
        
        response = renrenStore.requestJSON(params);
		if(response.length()==0){
			return;
		}
		Map<String, String> value = this.parseUserInfoJson(response);
		userId = value.get("uid");
		picUrl = value.get("tinyurl");
		userName = value.get("name");
		renrenLoginTime = loadSavedTime("renren_login_time");
	}

	public void getKaixinUserInfo() {

		Kaixin kaixin = Kaixin.getInstance();

		try {
			Bundle bundle = new Bundle();
			bundle.putString("fields",
					"uid,name,logo50");
			// 获取当前登录用户的资料
			String jsonResult = kaixin.request(ctx,
					Constants.KAIXIN_INTERFACE_GETUSERINFO, bundle, Kaixin.GET_METHOD);
			if (jsonResult == null) {
				return;
			} else {
				KaixinError kaixinError = Util.parseRequestError(jsonResult);
				if (kaixinError != null) {
					return;
				} 
				else {
					JSONObject jsonObj = new JSONObject(jsonResult);
					if (jsonObj == null) {
						return;
					}
					kaixinUserId = jsonObj.getString("uid");
					kaixinUserName = jsonObj.getString("name");
					kaixinPicUrl = jsonObj.getString("logo50");
					kaixinLoginTime = loadSavedTime("kaixin_login_time");
				}
			}
		} catch (Exception e) {
			Log.e("MyTag", "getKaixinUserInfo Error", e);
		}
	}
	
	
	
	
	
	public void getSinaUserInfo() {
		try{
			sinaLoginTime = loadSavedTime("sina_login_time");
		}
		catch (Exception ex){
			ex.printStackTrace();
		}
	}
	
	public void getBangUserInfo() {
	}
	
	public void getTencentUserInfo() {
		Log.d("TAG" , "getTencentUserInfo") ;
		List<QParameter> params = new ArrayList<QParameter>(
				1);
		List<QParameter> files = new ArrayList<QParameter>(
				1);
		OauthKey authKey = new OauthKey();
		authKey.customKey = Constants.QWEIBO_APP_KEY ;
		authKey.customSecrect = Constants.QWEIBO_APP_SECRET;
		authKey.tokenKey = qWeiboAccessToken() ;
		authKey.tokenSecrect = qWeiboAccessTokenSecret() ;
		
		Log.d("TAG", "qWeiboAccessToken" + qWeiboAccessToken()) ;
		Log.d("TAG", "qWeiboAccessTokenSecret" + qWeiboAccessTokenSecret()) ;
		
		QWeiboRequest request = new QWeiboRequest();
		tencentLoginTime = loadSavedTime("tencent_login_time");
		
		try {
			String retStr = request.syncRequest("http://open.t.qq.com/api/user/info", 
					"GET", authKey, params, files) ;
			JSONObject obj = new JSONObject(retStr) ;
			JSONObject data_obj = obj.getJSONObject("data") ;
			if(data_obj.getString("head").equals("") ||
					data_obj.getString("head") == null){
				tencentPicUrl = "buildin:1" ;
			} else {
				tencentPicUrl = data_obj.getString("head") + "/40" ;
			}
			tencentUserName = data_obj.getString("nick") ;
			tencentUserId = data_obj.getString("name") ;
			setQWeiboImgUrl(tencentPicUrl) ;
			setQWeiboNickName(tencentUserName) ;
			setQWeiboName(tencentUserId) ;
			
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e){
			e.printStackTrace() ;
		}
	}
	

	public void sendRenrenNews(String content, String imageUrl, String appName, int actionType, String downloadLink) {

		Log.e("renren", imageUrl);
		
        Bundle params = new Bundle();
        params.putString("method", "feed.publishFeed");
        
        int length = content.length();
        if(length>190){
            params.putString("description", content.substring(0, 190));//主体内容
        }
        else{
            params.putString("description", content);
        }

        if(Constants.UPLOAD_ACTION_LOGIN == actionType)
        {
            params.putString("name", ctx.getResources().getString(R.string.app_name));//标题
            params.putString("action_name", ctx.getResources().getString(R.string.txt_download_android_share));//底部链接文字
            params.putString("action_link", "http://www.bangcle.com/download");//底部链接地址
            params.putString("url", "http://www.bangcle.com/personal_pro.html");//图片及标题链接
        }
        else
        {
            params.putString("name", appName);//标题
            params.putString("action_name", ctx.getResources().getString(R.string.txt_download_application, appName));//底部链接文字
            params.putString("action_link", downloadLink);//底部链接地址
            params.putString("url", downloadLink);//图片及标题链接
        }
        

		if(!"".equalsIgnoreCase(imageUrl) && null!=imageUrl ){
			if(-1==imageUrl.indexOf("http:")){
				imageUrl = Constants.SERVER_ICON_URL + imageUrl;
			}
        	params.putString("image", imageUrl);
		}
        
        String response = renrenStore.requestJSON(params);
		if(response.length()==0){
			return;
		}
	}

	public boolean sendKaixinNews(String content, String imageUrl, String appName, int actionType, String downloadLink) 
	{
		Log.e("kaixin", imageUrl);

		Kaixin kaixin = Kaixin.getInstance();
		
		try{
	        Bundle bundle = new Bundle();

	        int length = content.length();
	        if(length>190){
		        bundle.putString("content", content.substring(0, 190));
	        }
	        else{
		        bundle.putString("content", content);
	        }
	        
			if(!"".equalsIgnoreCase(imageUrl) && null!=imageUrl ){
				if(-1==imageUrl.indexOf("http:")){
					imageUrl = Constants.SERVER_ICON_URL + imageUrl;
				}
		        bundle.putString("picurl", imageUrl);
			}
	        
			String jsonResult = kaixin.uploadContent(ctx,
					Constants.KAIXIN_INTERFACE_POSTRECORD, bundle, null);

			if (jsonResult == null) {
				return false;
			} 
			else {
				KaixinError kaixinError = Util.parseRequestError(jsonResult);
				if (kaixinError != null) {
					return false;
				} 
				else {
					JSONObject jsonObj = new JSONObject(jsonResult);
					if (jsonObj == null) {
						return false;
					}

					long rid = jsonObj.optInt("rid");
					if (rid > 0) {
						return true;
					} 
					else {
						return false;
					}
				}
			}
		}
		catch (Exception e) {
			Log.e("MyTag", "sendKaixinNews Error", e);
			return false;
		}
        
	}

	public String getAccountUserId(int snsType) {
		
		switch(snsType){
			case Constants.SNS_INDEX_SINA://sina
				return Long.toString(sinaUser.getId());
			case Constants.SNS_INDEX_TENCENT://tencent
				return tencentUserId;
			case Constants.SNS_INDEX_RENREN://renren
				return userId;
			case Constants.SNS_INDEX_KAIXIN://kaixin
				return kaixinUserId;
			default:
				return "";
		}
	}
	public String getAccountScreenName(int snsType) {

		String retName;
		switch(snsType){
			case Constants.SNS_INDEX_SINA://sina
				SharedPreferences sp = ctx.getSharedPreferences(Constants.PRE_USER_INFO, Context.MODE_WORLD_READABLE);
				retName = sp.getString(Constants.USER_NAME, "");
				return retName;
			case Constants.SNS_INDEX_TENCENT://tencent
				return tencentUserName;
			case Constants.SNS_INDEX_RENREN://renren
				return userName;
			case Constants.SNS_INDEX_KAIXIN://kaixin
				return kaixinUserName;
			default:
				return "";
		}
		
	}

	public String getAccountProfileImageURL(int snsType) {
		
		String retUrl;
		switch(snsType){
		case Constants.SNS_INDEX_SINA://sina
			SharedPreferences sp = ctx.getSharedPreferences(Constants.PRE_USER_INFO, Context.MODE_WORLD_READABLE);
			retUrl = sp.getString(Constants.USER_IMAGE, "");
			return retUrl;
		case Constants.SNS_INDEX_TENCENT://tencent
			return tencentPicUrl;
		case Constants.SNS_INDEX_RENREN://renren
			return picUrl;
		case Constants.SNS_INDEX_KAIXIN://kaixin
			return kaixinPicUrl;
		default:
			return "";
			}
		
	}

	public String getLastLoginTimeString(int snsType) {
		
		switch(snsType){
		case Constants.SNS_INDEX_SINA://sina
			return sinaLoginTime;
		case Constants.SNS_INDEX_TENCENT://tencent
			return tencentLoginTime;
		case Constants.SNS_INDEX_RENREN://renren
			return renrenLoginTime;
		case Constants.SNS_INDEX_KAIXIN://kaixin
			return kaixinLoginTime;
		default:
			return "";
			}
	}
	


	public void storeSinaAccountInfoToLocal(String uid) {

		SharedPreferences sp = ctx.getSharedPreferences(Constants.PRE_USER_INFO, Context.MODE_WORLD_READABLE);
		String sinaName = sp.getString(Constants.USER_NAME, "");
		
		sp = ctx.getSharedPreferences(Constants.PRE_USER_INFO, Context.MODE_PRIVATE);
		sp.edit().putString(Constants.USER_ID, Long.toString(sinaUser.getId())).commit();
		sp.edit().putString(Constants.USER_NAME, sinaUser.getScreenName()).commit();
		sp.edit().putString(Constants.USER_IMAGE, sinaUser.getProfileImageURL().toString()).commit();

	}

	public void storeRenrenAccountInfoToLocal() {
		
		SharedPreferences sp = ctx.getSharedPreferences(Constants.PRE_USER_INFO, Context.MODE_PRIVATE);
		sp.edit().putString(Constants.RENREN_USER_ID, userId).commit();
		sp.edit().putString(Constants.RENREN_USER_NAME, userName).commit();
		sp.edit().putString(Constants.RENREN_USER_IMAGE, picUrl).commit();
		
	}

	public void storeTencentAccountInfoToLocal(String uid) {
		SharedPreferences sp = ctx.getSharedPreferences(Constants.PRE_USER_INFO, Context.MODE_PRIVATE);
		sp.edit().putString(Constants.QWEIBO_USER_ID, tencentUserId).commit();
		sp.edit().putString(Constants.QWEIBO_USER_NAME, tencentUserName).commit();
		sp.edit().putString(Constants.QWEIBO_USER_IMAGE, tencentPicUrl).commit();
	}

	public void storeKaixinAccountInfoToLocal() {
		SharedPreferences sp = ctx.getSharedPreferences(Constants.PRE_USER_INFO, Context.MODE_PRIVATE);
		sp.edit().putString(Constants.KAIXIN_USER_ID, kaixinUserId).commit();
		sp.edit().putString(Constants.KAIXIN_USER_NAME, kaixinUserName).commit();
		sp.edit().putString(Constants.KAIXIN_USER_IMAGE, kaixinPicUrl).commit();
	}
	
	public void storeRenrenAccountInfoToMain() {
		setNickName(userName);
		setAvatarName(picUrl);
	}
	public void storeSinaAccountInfoToMain() {
		SharedPreferences sp = ctx.getSharedPreferences(Constants.PRE_USER_INFO, Context.MODE_WORLD_READABLE);
		String retName = sp.getString(Constants.USER_NAME, "");
		String retUrl = sp.getString(Constants.USER_IMAGE, "");
		setNickName(retName);
		setAvatarName(retUrl);
	}
	public void storeTencentAccountInfoToMain() {
		setNickName(tencentUserName);
		setAvatarName(tencentPicUrl);
	}
	public void storeKaixinAccountInfoToMain() {
		setNickName(kaixinUserName);
		setAvatarName(kaixinPicUrl);
	}
	
	public String getRenrenUidString() {
		return userId;
	}
	public String getRenrenUserNameString() {
		return userName;
	}
	public String getRenrenPicUrlString() {
		return picUrl;
	}

	public String getKaixinUidString() {
		return kaixinUserId;
	}
	public String getKaixinUserNameString() {
		return kaixinUserName;
	}
	public String getKaixinPicUrlString() {
		return kaixinPicUrl;
	}


	
	
	public void uploadAccountStatus(String rawMsg, String msg, boolean hasPic, 
			ImageItem pic, String picUrl, String appName, int actionType, String downloadLink){

		if(accountLogin[1]){
			uploadSinaAccountStatus(msg, hasPic, pic);
		}
		if(accountLogin[2]){
		}
		if(accountLogin[3]){
			sendRenrenNews(rawMsg, picUrl, appName, actionType, downloadLink);
		}
		if(accountLogin[4]){
			sendKaixinNews(rawMsg, picUrl, appName, actionType, downloadLink);
		}
		
	}
	

	private void uploadSinaAccountStatus(String msg, boolean hasPic, ImageItem pic){
		try
		{
			Status status;
			SharedPreferences sp = ctx.getSharedPreferences(Constants.PRE_USER_INFO, Context.MODE_WORLD_READABLE);
			token = sp.getString(Constants.ACCESS_TOKEN, "");
			tokenSecret = sp.getString(Constants.ACCESS_TOKEN_SECRET, "");
			Weibo mySinaWeibo= new Weibo();
			mySinaWeibo.setToken(token, tokenSecret);
			if(hasPic){
				status = mySinaWeibo.uploadStatus(msg, pic);
			}
			else{
				status = mySinaWeibo.updateStatus(msg);
			}
			Log.d("MyTag", "Successfully upload the status to [" + status.getText() + "].");

		} catch (WeiboException e)
		{
			e.printStackTrace();
		}
	}

    private String parseUserIdJson(String json) {
    	String uidStr = "";
    	int offset = json.lastIndexOf("\"uid\":");
    	int endOffset = json.lastIndexOf("}");
    	if(offset>=0){
    		uidStr = json.substring(offset+6, endOffset);
    	}
        return uidStr;
    }

    private Map<String, String> parseUserInfoJson(String json) {
        Map<String, String> d = new HashMap<String, String>();
        try {
            JSONArray userInfo = new JSONArray(json);
            if(userInfo.length()>0){
                Object obj = userInfo.get(0);
                JSONObject jobj = new JSONObject(obj.toString());
                d.put("uid", jobj.getString("uid"));
                d.put("tinyurl", jobj.getString("tinyurl"));
                d.put("name", jobj.getString("name"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return d;
    }

	public void SaveCurrentTime(String keyword)
	{
		String timeString = "";
		Time time = new Time();
		time.setToNow();
		timeString += time.year;
		timeString += "@";
		timeString += time.month+1;
		timeString += "@";
		timeString += time.monthDay;
		
		SharedPreferences sp = ctx.getSharedPreferences(Constants.PRE_USER_INFO, Context.MODE_PRIVATE);
		sp.edit().putString(keyword, timeString).commit();
	}

	public String loadSavedTime(String keyword)
	{
		SharedPreferences sp = ctx.getSharedPreferences(Constants.PRE_USER_INFO, Context.MODE_WORLD_READABLE);
		String timeString = sp.getString(keyword, "");

		Time time = new Time();
		time.year = 0;
		time.month = 0;
		time.monthDay = 0;
		
		if("".equalsIgnoreCase(timeString)){
			return "";
		}
		
		int start=0;
		int end;
		end = timeString.indexOf("@");
		time.year = Integer.parseInt(timeString.substring(start, end));
		
		start = end+1;
		end = timeString.indexOf("@", start);
		time.month = Integer.parseInt(timeString.substring(start, end));
		
		start = end+1;
		time.monthDay = Integer.parseInt(timeString.substring(start));

		String dateString = ctx.getResources().getString(R.string.label_date,
				time.year, time.month, time.monthDay);
		
		return dateString;
	}
	
	
	
	
	
	
	
	
	/*************** USER DATA ********************************/
	private static final String USER_DATA_PREF = "user_data2";
	/* UID */
	public static final String UID_KEY = "uid";
	public void setUid( String uid) {
		SharedPreferences sp = ctx.getSharedPreferences(USER_DATA_PREF, 
				ctx.MODE_PRIVATE);
		Editor spEditor = sp.edit();
		spEditor.putString(UID_KEY, uid);
		spEditor.commit();
		
		if(null==uid || "".equalsIgnoreCase(uid)){
			accountLogin[0] = false;
		}
		else{
			accountLogin[0] = true;
		}
	}
	
	public String getUid() {
		SharedPreferences sp = ctx.getSharedPreferences(USER_DATA_PREF, Context.MODE_WORLD_READABLE);
		String uid = sp.getString(UID_KEY, "");
		return uid;
	}
	
	

	/* Android ID */
	public static final String ANDROID_ID_KEY = "androidId";
	public void setAndroidId( String androidId) {
		SharedPreferences sp = ctx.getSharedPreferences(USER_DATA_PREF, 
				ctx.MODE_PRIVATE);
		Editor spEditor = sp.edit();
		spEditor.putString(ANDROID_ID_KEY, androidId);
		spEditor.commit();
	}
	
	public String getAndroidId() {
		SharedPreferences sp = ctx.getSharedPreferences(USER_DATA_PREF, Context.MODE_WORLD_READABLE);
		String androidId = sp.getString(ANDROID_ID_KEY, "");
		return androidId;
	}
	
	
	/* nickname */
	public static final String NICKNAME_KEY = "nickname";
	public void setNickName(String nickname) {
		Log.e("Nick", "setNickName");
		if("".equalsIgnoreCase(nickname)){
			Log.e("Nick", "01");
			return;
		}
		
		String savedNickName = getNickName();
		Log.e("Nick", savedNickName);
		if(!"".equalsIgnoreCase(savedNickName)){
			Log.e("Nick", "02");
			return;
		}
		
		Log.e("Nick", "03");
		
		SharedPreferences sp = ctx.getSharedPreferences(USER_DATA_PREF, Context.MODE_PRIVATE);
		Editor spEditor = sp.edit();
		spEditor.putString(NICKNAME_KEY, nickname);
		spEditor.commit();
	}
	
	public String getNickName() {
		SharedPreferences sp = ctx.getSharedPreferences(USER_DATA_PREF, Context.MODE_WORLD_READABLE);
		String uid = sp.getString(NICKNAME_KEY, "");
		return uid;
	}
	
	/* avatar */
	public static final String USER_AVATAR_KEY = "avatar";
	public void setAvatarName(String avatar) {
		Log.e("Nick", "setAvatarName");
		if("".equalsIgnoreCase(avatar)){
			Log.e("Nick", "01");
			return;
		}
		
		String curAvatarName = getAvatarName();
		Log.e("Nick", curAvatarName);
		if(!"".equalsIgnoreCase(curAvatarName)){
			Log.e("Nick", "02");
			return;
		}

		Log.e("Nick", "03");
		
		SharedPreferences sp = ctx.getSharedPreferences(USER_DATA_PREF, 
				Context.MODE_PRIVATE);
		Editor spEditor = sp.edit();
		spEditor.putString(USER_AVATAR_KEY, avatar);
		spEditor.commit();
	}

	public void overrideAvatarName(String avatar) {
		if("".equalsIgnoreCase(avatar)){
			return;
		}
		SharedPreferences sp = ctx.getSharedPreferences(USER_DATA_PREF, 
				Context.MODE_PRIVATE);
		Editor spEditor = sp.edit();
		spEditor.putString(USER_AVATAR_KEY, avatar);
		spEditor.commit();
	}
	
	public String getAvatarName() {
		SharedPreferences sp = ctx.getSharedPreferences(USER_DATA_PREF, Context.MODE_WORLD_READABLE);
		String avatar = sp.getString(USER_AVATAR_KEY, "");
		return avatar;		
	}
	
	/***************************SPLASH_ACTIVITY ***************************/
	private static final String SPLASH_ACTIVITY_PREF = "SplashActivity";
	
	
	
	public void setRenren( Renren renren) {
		this.renrenStore = renren;
	}
	public Renren getRenren() {
		return this.renrenStore;
	}

	public void setAsyncRenren( AsyncRenren asyncRenren) {
		this.asyncRenren = asyncRenren;
	}
	public AsyncRenren getAsyncRenren() {
		return this.asyncRenren;
	}
	
	/***************************remind note ***************************/
	public static final String REMIND_PREF = "remind_pref" ;
	public static final String NOTE_COUNT = "note_count" ;
	//新活动（提醒）
	public void setNoteCounts(int count){
		SharedPreferences sp = ctx.getSharedPreferences(REMIND_PREF, 
				Context.MODE_PRIVATE) ;
		SharedPreferences.Editor editor = sp.edit();
		editor.putInt(NOTE_COUNT, count);
		editor.commit();
	}
	public int NoteCount(){
		SharedPreferences sp = ctx.getSharedPreferences(REMIND_PREF, 
				Context.MODE_PRIVATE);
		int count = sp.getInt(NOTE_COUNT, 0);
		return count;
	}
	
	//新粉丝
	public static final String FOLLOWER_COUNT = "follower_count" ;
	public void setFollowerCounts(int count){
		SharedPreferences sp = ctx.getSharedPreferences(REMIND_PREF, 
				Context.MODE_PRIVATE) ;
		SharedPreferences.Editor editor = sp.edit();
		editor.putInt(FOLLOWER_COUNT, count);
		editor.commit();
	}
	public int FollowerCount(){
		SharedPreferences sp = ctx.getSharedPreferences(REMIND_PREF, 
				Context.MODE_PRIVATE);
		int count = sp.getInt(FOLLOWER_COUNT, 0);
		return count;
	}
	
	//新私信
	public static final String SMS_COUNT = "followed_count" ;
	public void setSMSCounts(int count){
		SharedPreferences sp = ctx.getSharedPreferences(REMIND_PREF, 
				Context.MODE_PRIVATE) ;
		SharedPreferences.Editor editor = sp.edit();
		editor.putInt(SMS_COUNT, count);
		editor.commit();
	}
	public int SMSCount(){
		SharedPreferences sp = ctx.getSharedPreferences(REMIND_PREF, 
				Context.MODE_PRIVATE);
		int count = sp.getInt(SMS_COUNT, 0);
		return count;
	}
	
	//新勋章
	public static final String HONOR_COUNT = "honor_count" ;
	public void setHonorCounts(int count){
		SharedPreferences sp = ctx.getSharedPreferences(REMIND_PREF, 
				Context.MODE_PRIVATE) ;
		SharedPreferences.Editor editor = sp.edit();
		editor.putInt(HONOR_COUNT, count);
		editor.commit();
	}
	public int honorCount(){
		SharedPreferences sp = ctx.getSharedPreferences(REMIND_PREF, 
				Context.MODE_PRIVATE);
		int count = sp.getInt(HONOR_COUNT, 0);
		return count;
	}

	/* 新提醒 */
	public static final String REMIND_SMS_MD5_KEY = "remind_sms_md5";
	public void setRemindSmsMd5( String remindSmsMd5) {
		SharedPreferences sp = ctx.getSharedPreferences(USER_DATA_PREF, 
				ctx.MODE_PRIVATE);
		Editor spEditor = sp.edit();
		spEditor.putString(REMIND_SMS_MD5_KEY, remindSmsMd5);
		spEditor.commit();
	}
	public String getRemindSmsMd5() {
		SharedPreferences sp = ctx.getSharedPreferences(USER_DATA_PREF, Context.MODE_WORLD_READABLE);
		String androidId = sp.getString(REMIND_SMS_MD5_KEY, "");
		return androidId;
	}

	public static final String REMIND_FAN_MD5_KEY = "remind_fan_md5";
	public void setRemindFanMd5( String remindSmsMd5) {
		SharedPreferences sp = ctx.getSharedPreferences(USER_DATA_PREF, 
				ctx.MODE_PRIVATE);
		Editor spEditor = sp.edit();
		spEditor.putString(REMIND_FAN_MD5_KEY, remindSmsMd5);
		spEditor.commit();
	}
	public String getRemindFanMd5() {
		SharedPreferences sp = ctx.getSharedPreferences(USER_DATA_PREF, Context.MODE_WORLD_READABLE);
		String androidId = sp.getString(REMIND_FAN_MD5_KEY, "");
		return androidId;
	}
	
	public static final String REMIND_HONOR_MD5_KEY = "remind_honor_md5";
	public void setRemindHonorMd5( String remindHonorMd5) {
		SharedPreferences sp = ctx.getSharedPreferences(USER_DATA_PREF, 
				ctx.MODE_PRIVATE);
		Editor spEditor = sp.edit();
		spEditor.putString(REMIND_HONOR_MD5_KEY, remindHonorMd5);
		spEditor.commit();
	}
	public String getRemindHonorMd5() {
		SharedPreferences sp = ctx.getSharedPreferences(USER_DATA_PREF, Context.MODE_WORLD_READABLE);
		String androidId = sp.getString(REMIND_HONOR_MD5_KEY, "");
		return androidId;
	}
	
	/***************************腾讯微博相关***************************/
	public static String QWEIBO_PREF = "qweibo_pref" ;
	public static String QWEIBO_ACCESS_TOKEN = "qweibo_access_token" ;
	public static String QWEIBO_ACCESS_TOKEN_SECRET = "qweibo_access_token_secret" ;
	public static String QWEIBO_NAME = "qweibo_name" ;
	public static String QWEIBO_IMG_URL = "qweibo_img_url" ;
	public static String QWEIBO_NICK_NAME = "qweibo_nick_name" ;
	
	public void setQWeiboAccessToken(String accessToken){
		SharedPreferences sp = ctx.getSharedPreferences(QWEIBO_PREF, 
				Context.MODE_PRIVATE) ;
		SharedPreferences.Editor editor = sp.edit();
		editor.putString(QWEIBO_ACCESS_TOKEN, accessToken);
		editor.commit();
	}
	public String qWeiboAccessToken(){
		SharedPreferences sp = ctx.getSharedPreferences(QWEIBO_PREF, 
				Context.MODE_WORLD_READABLE);
		String access_token = sp.getString(QWEIBO_ACCESS_TOKEN , "");
		return access_token;
	}
	
	public void setQWeiboAccessTokenSecret(String accessTokenSecret){
		SharedPreferences sp = ctx.getSharedPreferences(QWEIBO_PREF, 
				Context.MODE_PRIVATE) ;
		SharedPreferences.Editor editor = sp.edit();
		editor.putString(QWEIBO_ACCESS_TOKEN_SECRET, accessTokenSecret);
		editor.commit();
	}
	public String qWeiboAccessTokenSecret(){
		SharedPreferences sp = ctx.getSharedPreferences(QWEIBO_PREF, 
				Context.MODE_WORLD_READABLE);
		String access_token_secret = sp.getString(QWEIBO_ACCESS_TOKEN_SECRET , "");
		return access_token_secret;
	}
	
	public void setQWeiboName(String name){
		SharedPreferences sp = ctx.getSharedPreferences(QWEIBO_PREF, 
				Context.MODE_PRIVATE) ;
		SharedPreferences.Editor editor = sp.edit();
		editor.putString(QWEIBO_NAME, name);
		editor.commit();
	}
	public String qWeiboName(){
		SharedPreferences sp = ctx.getSharedPreferences(QWEIBO_PREF, 
				Context.MODE_PRIVATE);
		String name = sp.getString(QWEIBO_NAME , "");
		return name;
	}
	
	public void setQWeiboImgUrl(String imgUrl){
		SharedPreferences sp = ctx.getSharedPreferences(QWEIBO_PREF, 
				Context.MODE_PRIVATE) ;
		SharedPreferences.Editor editor = sp.edit();
		editor.putString(QWEIBO_IMG_URL, imgUrl);
		editor.commit();
	}
	public String qWeiboImgUrl(){
		SharedPreferences sp = ctx.getSharedPreferences(QWEIBO_PREF, 
				Context.MODE_PRIVATE);
		String imgUrl = sp.getString(QWEIBO_IMG_URL , "");
		return imgUrl;
	}
	
	public void setQWeiboNickName(String nickName){
		SharedPreferences sp = ctx.getSharedPreferences(QWEIBO_PREF, 
				Context.MODE_PRIVATE) ;
		SharedPreferences.Editor editor = sp.edit();
		editor.putString(QWEIBO_NICK_NAME, nickName);
		editor.commit();
	}
	public String qWeiboNickName(){
		SharedPreferences sp = ctx.getSharedPreferences(QWEIBO_PREF, 
				Context.MODE_PRIVATE);
		String nickName = sp.getString(QWEIBO_NICK_NAME , "");
		return nickName;
	}
	
	/*****************系统相关*****************/
	public static String SYSTEM_PREF = "system_pref" ;
	public static String APPLICATION_SHORTCUT_CREATED = "application_shortcut_created" ;
	public static String USER_ICON_SHORTCUT_CREATED = "user_icon_shortcut_created" ;
	
	public void setApplicationShortCutCreated(boolean b){
		SharedPreferences sp = ctx.getSharedPreferences(SYSTEM_PREF, 
				Context.MODE_PRIVATE) ;
		SharedPreferences.Editor editor = sp.edit();
		editor.putBoolean(APPLICATION_SHORTCUT_CREATED, b);
		editor.commit();
	}
	public boolean ApplicationShortCutCreated(){
		SharedPreferences sp = ctx.getSharedPreferences(SYSTEM_PREF, 
				Context.MODE_PRIVATE);
		boolean b = sp.getBoolean(APPLICATION_SHORTCUT_CREATED , false);
		return b;
	}
	
	
	public void setUserIconShortCutCreated(boolean b){
		SharedPreferences sp = ctx.getSharedPreferences(SYSTEM_PREF, 
				Context.MODE_PRIVATE) ;
		SharedPreferences.Editor editor = sp.edit();
		editor.putBoolean(USER_ICON_SHORTCUT_CREATED, b);
		editor.commit();
	}
	public boolean UserIconShortCutCreated(){
		SharedPreferences sp = ctx.getSharedPreferences(SYSTEM_PREF, 
				Context.MODE_PRIVATE);
		boolean b = sp.getBoolean(USER_ICON_SHORTCUT_CREATED , false);
		return b;
	}
	

	public Activity getStoredActivity(){
		return storedActivity;
	}
	public void setStoredActivity(Activity activity){
		storedActivity = activity;
	}
}
